package com.gitee.maskit.web;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.Ordered;

@Configuration
public class MaskitWebAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public static MaskitWebProperties maskitWebProperties() {
        return new MaskitWebProperties();
    }

    @Bean
    public FilterRegistrationBean webFilter() {
        final FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebFilter());
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        bean.setName(WebFilter.NAME);
        return bean;
    }

    @Bean
    @ConditionalOnMissingBean(ReloadableResourceBundleMessageSource.class)
    @Primary
    public static ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource(MaskitWebProperties properties) {
        final ReloadableResourceBundleMessageSource source =
            new ReloadableResourceBundleMessageSource();
        if (null != properties.getMessages()) {
            source.setBasenames(properties.getMessages().toArray(
                new String[properties.getMessages().size()]));
        } else {
            source.setBasenames("classpath:messages", "messages");
        }
        source.setDefaultEncoding("UTF-8");
        return source;
    }

    @Bean
    @ConditionalOnBean(value = ReloadableResourceBundleMessageSource.class)
    public static MaskitResponseAdviceProcessor maskitResponseAdviceProcessor(ReloadableResourceBundleMessageSource source) {
        return new MaskitResponseAdviceProcessor(source);
    }
}
